package com.logos.musicframe.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.logos.musicframe.chatmemory.ChatHistoryRepository;
import com.logos.musicframe.req.ChatReq;
import com.logos.musicframe.result.Result;
import com.logos.musicframe.utils.UserInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

/**
 * @author logos
 * date 2025/6/17 14:17
 * @version v1.0
 * @Package com.logos.musicframe.controller
 */
@Component
@Slf4j
public class ChatController {


    @Autowired
    @Qualifier("openAiChatClient")
    private ChatClient openAiChatClient;

    @Autowired
    private UserInfoUtil userInfoUtil;

    @Autowired
    private ChatHistoryRepository chatHistoryRepository;

    /**
     * ai对话基本实现
     * @param message
     * @return
     */
    public Result<String> chat(String message){
        try {
            log.info("ChatController.chat.message{}", message);
            String answer = openAiChatClient.prompt()
                    .user(message)
                    .call()
                    .content();
            return Result.ok( answer);
        }catch (Exception e){
            log.error("ChatController.chat.error{}", e);
            return Result.fail("聊天失败");
        }
    }

    /**
     * ai聊天伴随聊天会话
     * @param chatReq
     * @return
     */
    public Result<String> chatWithChatId(ChatReq chatReq){
        try {
            if (log.isInfoEnabled()) {
                log.info("ChatController.chatWithSession.chatReq:{}", JSON.toJSONString(chatReq));
            }
            Preconditions.checkNotNull(chatReq.getMessage(), "消息不能为空");
            Preconditions.checkNotNull(chatReq.getChatId(), "会话id不能为空");
            String chatId = chatReq.getChatId();
            chatHistoryRepository.save(chatId, String.valueOf(userInfoUtil.getUserId()));
            // 2.请求模型
            String result = openAiChatClient.prompt()
                    .user(chatReq.getMessage())
                    .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                    .call()
                    .content();
            return  Result.ok(result);
        }catch (Exception e){
            log.error("ChatController.chatWithSession.error{}", e);
            return Result.fail("聊天失败");
        }
    }
}
